package com.bookmanagement.service.impl;

import com.bookmanagement.DTO.BookDTO;
import com.bookmanagement.DTO.BookSearchDTO;
import com.bookmanagement.constant.BookException;
import com.bookmanagement.entity.Book;
import com.bookmanagement.entity.Comment;
import com.bookmanagement.exception.BusinessException;
import com.bookmanagement.mapper.BookMapper;
import com.bookmanagement.mapper.CategoryMapper;
import com.bookmanagement.mapper.CommentMapper;
import com.bookmanagement.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author skyjay
 */
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Override
    public List<Book> getRecommendBooks() {
        List<Book> recommendBooks =bookMapper.getRecommendBooks();
        return recommendBooks;
    }

    @Override
    public BookDTO getBookById(Integer id) {
        Book book = bookMapper.getByIdWithStatus(Long.valueOf(id));
        if (book == null) {
            throw new BusinessException(BookException.BOOK_NOT_FOUND);
        }
        String category=categoryMapper.getCategoryById(Math.toIntExact(book.getCategoryId()));
        
        // 查询该图书的所有评论
        List<Comment> comments = commentMapper.getCommentsByBookId(Long.valueOf(id));
        
        return BookDTO.builder()
                .title(book.getTitle())
                .isbn(book.getIsbn())
                .author(book.getAuthor())
                .description(book.getDescription())
                .categoryId(book.getCategoryId())
                .category(category)
                .coverUrl(book.getCoverUrl())
                .publishDate(book.getPublishDate())
                .stock(book.getStock())
                .comments(comments)
                .build();
    }

    @Override
    public List<BookDTO> searchBook(BookSearchDTO bookSearchDTO) {
        List<Book> books = bookMapper.searchBook(bookSearchDTO);
        List<BookDTO> bookDTOS = new ArrayList<>(books.size());
        for (Book book : books) {
            BookDTO bookDTO = BookDTO.builder()
                    .title(book.getTitle())
                    .isbn(book.getIsbn())
                    .author(book.getAuthor())
                    .description(book.getDescription())
                    .categoryId(book.getCategoryId())
                    .category(categoryMapper.getCategoryById(Math.toIntExact(book.getCategoryId())))
                    .coverUrl(book.getCoverUrl())
                    .publishDate(book.getPublishDate())
                    .stock(book.getStock())
                    .build();
            bookDTOS.add(bookDTO);
        }
        return bookDTOS;
    }

    @Override
    public void addBook(BookDTO bookDTO) {
        // 验证categoryId是否为空
        if (bookDTO.getCategoryId() == null) {
            throw new BusinessException("请选择图书分类");
        }
        
        // 验证分类是否存在
        String categoryName = categoryMapper.getCategoryById(Math.toIntExact(bookDTO.getCategoryId()));
        if (categoryName == null) {
            throw new BusinessException("选择的分类不存在");
        }
        
        Book book = Book.builder()
                .title(bookDTO.getTitle())
                .isbn(bookDTO.getIsbn())
                .author(bookDTO.getAuthor())
                .description(bookDTO.getDescription())
                .categoryId(bookDTO.getCategoryId())
                .coverUrl(bookDTO.getCoverUrl())
                .publishDate(bookDTO.getPublishDate())
                .stock(bookDTO.getStock())
                .status(1) // 默认可借阅状态
                .build();
        bookMapper.insertBook(book);
    }

    @Override
    public void updateBook(Long id, BookDTO bookDTO) {
        Book book = bookMapper.getById(id);
        if (book == null) {
            throw new BusinessException(BookException.BOOK_NOT_FOUND);
        }
        
        // 如果修改了分类，验证新分类是否存在
        if (bookDTO.getCategoryId() != null) {
            String categoryName = categoryMapper.getCategoryById(Math.toIntExact(bookDTO.getCategoryId()));
            if (categoryName == null) {
                throw new BusinessException("选择的分类不存在");
            }
            book.setCategoryId(bookDTO.getCategoryId());
        }
        
        book.setTitle(bookDTO.getTitle());
        book.setIsbn(bookDTO.getIsbn());
        book.setAuthor(bookDTO.getAuthor());
        book.setDescription(bookDTO.getDescription());
        book.setCoverUrl(bookDTO.getCoverUrl());
        book.setPublishDate(bookDTO.getPublishDate());
        book.setStock(bookDTO.getStock());
        
        bookMapper.updateBook(book);
    }

    @Override
    public void deleteBook(Long id) {
        Book book = bookMapper.getById(id);
        if (book == null) {
            throw new BusinessException(BookException.BOOK_NOT_FOUND);
        }
        // 逻辑删除：将status设置为0
        bookMapper.deleteBook(id);
    }

    @Override
    public List<Book> getAllBooks() {
        return bookMapper.getAllBooks();
    }
}
